﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JYH.Data;
using Newtonsoft.Json;
using JYH.Model;
using JYH.DataAccess;
using JYH.Framework;
using JYH.Model.API;

namespace JYH.Business
{
    /// <summary>
    ///  WmsReciveOrderInfo
    /// </summary>
    public class WmsReciveOrderInfoBLL : BusinessBase<WmsReciveOrderInfo>
    {
        /// <summary>
        ///  WmsReciveOrderInfo
        /// </summary>
        public WmsReciveOrderInfoBLL()
        {
            myDataBase = DB.D();
            this.SqlSelect = @"; Select WmsReciveOrderInfo.*,
                             BasPartnerInfo.PartnerNO,BasPartnerInfo.PartnerName 
                             From WmsReciveOrderInfo
                             left join BasPartnerInfo on WmsReciveOrderInfo.PartnerID=BasPartnerInfo.PartnerID";
        }

        /// <summary>
        /// 保存WmsReciveOrderInfo 数据
        /// </summary>
        /// <param name="info"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool SaveWmsReciveOrderInfo(WmsReciveOrderInfo info, ref ResponseJson<WmsReciveOrderInfo> message)
        {
            Database db = DB.D();
            db.BeginTransaction();
            StringBuilder sb = new StringBuilder();
            Sql sql = new Sql();
            string Msg = string.Empty;
            WmsReciveOrderInfo orders = new WmsReciveOrderInfo();
            try
            {
                WmsReciveOrderInfoBLL orderInfoBLL = new WmsReciveOrderInfoBLL();
                sql.Append($"where WmsReciveOrderInfo.ReciveOrderID='{info.ReciveOrderID}'");
                orders = orderInfoBLL.GetSingeModel(sql);
                if (orders != null)
                {
                    orders.ReciveOrderNO = info.ReciveOrderNO;
                    orders.PartnerID = info.PartnerID;
                    orders.PatnerOrderNO = info.PatnerOrderNO;
                    orders.ERPNO = info.ERPNO;
                    orders.ReciveDate = info.ReciveDate;
                    orders.SourceOrderNO = info.SourceOrderNO;
                    orders.UpdateUser = SysUserInfoBLL.GetCookieUser().UserName;
                    sb.Append(BusinessTool.GetUpdateSql(orders));
                }
                else
                {
                    orders = new WmsReciveOrderInfo();
                    orders.ReciveOrderID = Guid.NewGuid().ToString();
                    orders.PartnerID = info.PartnerID;
                    orders.ERPNO = info.ERPNO;
                    orders.ReciveDate = info.ReciveDate;
                    orders.PatnerOrderNO = info.PatnerOrderNO;
                    orders.SourceOrderNO = info.SourceOrderNO;
                    orders.CreateUser = SysUserInfoBLL.GetCookieUser().UserName;
                    if (!string.IsNullOrWhiteSpace(info.ReciveOrderID))
                    {
                        orders.ReciveOrderNO = info.ReciveOrderNO;
                    }
                    else
                    {
                        orders.ReciveOrderNO = SysFormNOInfoBLL.GetLastFormNO("WmsReciveOrderInfo", out Msg);
                    }
                    sb.Append(BusinessTool.GetInsertSql(orders));
                }
                message.Items.Add(orders);

                if (sb.Length > 0)
                {
                    db.Execute(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                message.Message = ex.Message;
                db.AbortTransaction();
                return false;
            }
            db.CompleteTransaction();
            return true;
        }


        /// <summary>
        /// 收料单同步
        /// </summary>
        /// <param name="orders">收料单集合</param>
        /// <param name="Msg"></param>
        /// <returns></returns>
        public static bool SyncReciveOrder(List<WmsReciveOrderInfo> orders, out string Msg)
        {
            Msg = string.Empty;
            Database db = DB.D();
            db.BeginTransaction();
            StringBuilder sb = new StringBuilder();
            Sql sql = new Sql();

            try
            {

                string OrderNO = "'',";
                string SupplyNO = "'',";
                string MaterialNO = "'',";
                foreach (var item in orders)
                {
                    OrderNO += "'" + item.ReciveOrderNO + "',";

                    SupplyNO+= "'" + item.PartnerNO + "',";
                    foreach (WmsReciveItem obj in item.Items)
                    {
                        if (MaterialNO.IndexOf(obj.MaterialNO)< 0)
                        {
                            MaterialNO += "'" + StringHelper.ConvertFullWidthToHalfWidth( obj.MaterialNO) + "',";
                        }
                  
                    }
                }
                SupplyNO = SupplyNO.Substring(0, SupplyNO.Length-1);
                MaterialNO= MaterialNO.Substring(0, MaterialNO.Length - 1);
                OrderNO = OrderNO.Substring(0, OrderNO.Length - 1);
                List<BasMaterialInfo> Materials = new List<BasMaterialInfo>();
                sql = new Sql();
                sql.Append(@";Select BasMaterialInfo.* From BasMaterialInfo");
                sql.Where(@"BasMaterialInfo.MaterialNO  in (" + MaterialNO + ")");
                sql.OrderBy("BasMaterialInfo.MaterialNO");
                Materials = db.Fetch<BasMaterialInfo>(sql);
                List<BasPartnerInfo> Partners = new List<BasPartnerInfo>();
                sql = new Sql();
                sql.Append(@";Select BasPartnerInfo.* From BasPartnerInfo");
                sql.Where(@"BasPartnerInfo.PartnerNO  in (" + SupplyNO + ")");
                sql.OrderBy("BasPartnerInfo.PartnerNO");
                Partners = db.Fetch<BasPartnerInfo>(sql);

                List<BasWarehouseInfo> Warehouses = new List<BasWarehouseInfo>();
                sql = new Sql();
                sql.Append(@";Select BasWarehouseInfo.* From BasWarehouseInfo");
                sql.OrderBy("BasWarehouseInfo.WarehouseNO");
                Warehouses = db.Fetch<BasWarehouseInfo>(sql);
                sql = new Sql();
                sql.Append("Select WmsReciveOrderInfo.* From WmsReciveOrderInfo");
                sql.Where("WmsReciveOrderInfo.ReciveOrderNO in (" + OrderNO + ")");
                List<WmsReciveOrderInfo> OldOrders = new List<WmsReciveOrderInfo>();
                OldOrders=db.Fetch<WmsReciveOrderInfo>(sql);
                int count = 0;
                for (int i = 0; i < orders.Count; i++) 
                {

                    int index= OldOrders.FindIndex(p=>p.ReciveOrderNO == orders[i].ReciveOrderNO);
                    if (index < 0)
                    {
                        count++;
                        WmsReciveOrderInfo info = new WmsReciveOrderInfo();
                        info.ReciveOrderID = Guid.NewGuid().ToString();
                        info.ReciveOrderNO = orders[i].ReciveOrderNO;
                        info.ERPNO = orders[i].ERPNO;
                        info.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        info.RState = "2";
                        info.SourceOrderNO = orders[i].SourceOrderNO;
                        info.PatnerOrderNO = orders[i].PatnerOrderNO;
                        info.CreateUser = "Admin";
                        info.CreateTime = BusinessTool.GetDateTime();
                        info.ReciveDate = orders[i].ReciveDate;
                        int m= Partners.FindIndex(p=>p.PartnerNO == orders[i].PartnerNO);
                        if ((m>=0))
                        {
                            info.PartnerID = Partners[m].PartnerID;
                        }
                        m = -1;
                        m = Warehouses.FindIndex(p => p.WarehouseNO == orders[i].WarehouseNO);
                        if ((m >= 0))
                        {
                            info.WarehouseID = Warehouses[m].WarehouseID;
                        }
                        info.Items = new List<WmsReciveItem>();
                        sb.Append(BusinessTool.GetInsertSql(info));
                        foreach (var item in orders[i].Items)
                        {

                            WmsReciveItem obj = new WmsReciveItem();
                            obj.BatchNO = item.BatchNO;
                            obj.ReciveOrderID = info.ReciveOrderID;
                            obj.ReciveQty = item.ReciveQty;
                            obj.StockQty = 0;
                            obj.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            obj.RState = "0";
                            obj.ERPItem = item.ERPItem;
                            obj.LabelQty = item.ReciveQty;
                            obj.MaterialID = item.MaterialID;
                            obj.OKQty = item.ReciveQty;
                            obj.PackQty = item.PackQty;
                            obj.POItem=item.POItem;
                            obj.PONO=item.PONO;
                            obj.ReciveItemID = Guid.NewGuid().ToString();
                            m = -1;
                            m=Materials.FindIndex(p => p.MaterialNO.Replace('＋', '+').Replace('﹢', '+') == item.MaterialNO.Replace('＋', '+').Replace('﹢', '+'));

                            if (m >= 0)
                            {
                                obj.MaterialID = Materials[m].MaterialID;
                            }
                            
                           obj.BatchNO=item.BatchNO;

                            info.Items.Add(obj);
                            sb.Append(BusinessTool.GetInsertSql(obj));
                            count++;
                        }
                        OldOrders.Add(info);

                    }
                    else
                    {
                        count++;
                        int k = Partners.FindIndex(p => p.PartnerNO == orders[i].PartnerNO);
                        if ((k >= 0))
                        {
                            OldOrders[index].PartnerID = Partners[k].PartnerID;
                        }
                        k = -1;
                        k = Warehouses.FindIndex(p => p.WarehouseNO == orders[i].WarehouseNO);
                        if ((k >= 0))
                        {
                            OldOrders[index].WarehouseID = Warehouses[k].WarehouseID;
                        }
                        OldOrders[index].SourceOrderNO = orders[i].SourceOrderNO;
                        OldOrders[index].ReciveDate = orders[i].ReciveDate;
                        OldOrders[index].PatnerOrderNO = orders[i].PatnerOrderNO;
                        sb.Append(BusinessTool.GetUpdateSql(OldOrders[index]));
                        if (OldOrders[index].RState == "2"|| OldOrders[index].RState == "0"|| OldOrders[index].RState == "1")
                        {

                            sb.Append("Delete WmsReciveItem WHere WmsReciveItem.ReciveOrderID='"+ OldOrders[index].ReciveOrderID+ "'");
                            foreach (var item in orders[i].Items)
                            {

                                WmsReciveItem obj = new WmsReciveItem();
                                obj.BatchNO = item.BatchNO;
                                int m = Materials.FindIndex(p => StringHelper.ConvertFullWidthToHalfWidth( p.MaterialNO) ==  item.MaterialNO);
                                if (m >= 0)
                                {
                                    obj.MaterialID = Materials[m].MaterialID;
                                }
                                obj.ReciveItemID = Guid.NewGuid().ToString();
                                obj.ERPItem = item.ERPItem;
                                obj.ReciveOrderNO = item.ReciveOrderNO;
                                obj.ReciveOrderID = OldOrders[index].ReciveOrderID;
                                obj.ReciveQty = item.ReciveQty;
                                obj.LabelQty = item.ReciveQty;
                                obj.OKQty = item.ReciveQty;
                                obj.ReciveItemID = Guid.NewGuid().ToString();
                                obj.POItem = item.POItem;
                                obj.PONO = item.PONO;
                                // OldItems.Add(obj);
                                sb.Append(BusinessTool.GetInsertSql(obj));

                                count++;



                            }

                        }
                        
                 

                    }

                    if (count > 500&&!string.IsNullOrEmpty(sb.ToString()))
                    {
                        db.Execute(sb.ToString());
                        count = 0;
                        sb = new StringBuilder();
                    }
                }


                if (sb.Length > 0)
                {
                    db.Execute(sb.ToString());
                    count = 0;
                    sb = new StringBuilder();
                }


                db.CompleteTransaction();
                return true;
            }
            catch (Exception ex) 
            {
                Msg = ex.Message;
                db.AbortTransaction();
                return false;
            }
        }
    }
}